package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.JdbcTemplate.HaiweidaCooperativeSchoolJdbc;
import com.wuseguang.springcloud.dao.jdbc.OrganizationalStructureTemplate;
import com.wuseguang.springcloud.entity.ClassesList;
import com.wuseguang.springcloud.service.OrganizationalStructureService;
import com.wuseguang.springcloud.thread.HaiweidaDepartment;
import com.wuseguang.springcloud.thread.HaiweidaFacesThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class OrganizationalStructureServiceImpl implements OrganizationalStructureService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrganizationalStructureTemplate organizationalStructureTemplate;

    @Autowired
    private ClassCardFieldService service;
    @Autowired
    private HaiweidaCooperativeSchoolJdbc haiweidaCooperativeSchoolJdbc;

    /**
     * @描述 组织架构构造图
     * @创建人 zm
     * @创建时间 2019/12/7
     */
    @Override
    public Map<String, Object> queryOrganizationalStructure(String schoolId) {
        String sql3 = "SELECT id  schoolid,school_name schoolname FROM  school WHERE id=" + schoolId;
        List<Map<String, Object>> map1 = organizationalStructureTemplate.getMap1(sql3, "schoolid", "schoolname");
        String sql = "SELECT  m.id departmentid,m.name departmentname FROM department m  WHERE  m.school_id=" + schoolId;
        //部门
        List<Map<String, Object>> maps1 = organizationalStructureTemplate.getMap1(sql, "departmentid", "departmentname");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        //年级
        String sql1 = "SELECT  g.id gradeid,g.name gradename,other FROM grade g WHERE  g.school_id=" + schoolId + " ORDER BY other";
        List<Map<String, Object>> map11 = organizationalStructureTemplate.getMap2(sql1, "gradeid", "gradename", "other");
        if (map11 != null && map11.size() > 0) {
            for (Map<String, Object> stringObjectMap1 : map11) {
                String sql2 = "SELECT s.id classid ,s.name classname FROM  classes s WHERE  s.grade_id=" + stringObjectMap1.get("gradeid") + " and s.school_id=" + schoolId;
                //班级
                List<Map<String, Object>> map12 = organizationalStructureTemplate.getMap1(sql2, "classid", "classname");
                stringObjectMap1.put("classlist", map12);
            }
            stringObjectHashMap.put("gradelist", map11);
        }
        if (map1 != null) {
            map1.get(0).put("departmentlist", maps1);
            map1.get(0).putAll(stringObjectHashMap);
            return map1.get(0);
        }
        return null;
    }


    /**
     * @描述 左边组织架构图展示区
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public Map<String, Object> queryOrganizationalStructure1(String schoolId) {
        if (schoolId.isEmpty()) {
            return null;
        }
        //创建 其他目录
        String sql5 = "INSERT INTO grade(name,school_id,department_id,other,education_id) VALUES (?,?,?,?,?)";
        String sq3 = "SELECT COUNT(1) count FROM grade WHERE school_id=? AND other=1";
        String sq6 = "SELECT COUNT(1) count FROM department WHERE school_id=?";
        String sq7 = "INSERT INTO department(name,school_id) VALUES(?,?)";
        Long did = 0L;
        if (organizationalStructureTemplate.queryCount(sq6, schoolId) == 0) {
            did = organizationalStructureTemplate.updateByParameterGetId(sq7, "教务部", schoolId);
        }
        if (organizationalStructureTemplate.queryCount(sq3, schoolId) == 0) { //创建其他
            organizationalStructureTemplate.updateByParameter(sql5, "其他", schoolId, did, 1, 1);
        }
        String sql3 = "SELECT id  schoolid,school_name schoolname," +
                "IF((SELECT COUNT(*) FROM department m  WHERE m.school_id=school.id AND school.id=" + schoolId + " )>0,1,0 ) state FROM  school WHERE id=" + schoolId;
        List<Map<String, Object>> map1 = organizationalStructureTemplate.getMap2(sql3, "schoolid", "schoolname", "state");
        String sql = "SELECT  m.id departmentid,m.name departmentname  FROM department m  WHERE  m.school_id=" + schoolId + " order by id";
        //部门
        List<Map<String, Object>> maps1 = organizationalStructureTemplate.queryDepartment(sql, "departmentid", "departmentname", schoolId);
        if (map1 != null && map1.get(0) != null) {
            map1.get(0).put("departmentlist", maps1);
            return map1.get(0);
        }
        return null;
    }

    /**
     * @描述 批量生成部门年级和班级
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int batchAddition(String schoolId, String education_id) {
        int a = 0;
        try {
            String sq3 = "SELECT id count FROM department WHERE school_id=? order by id LIMIT 1";
            Integer integer = organizationalStructureTemplate.queryCount(sq3, schoolId);
            String sql = "INSERT INTO grade(name,school_id,department_id,other,education_id) VALUES (?,?,?,0,?)";
            String sql1 = "INSERT INTO classes(NAME,school_id,grade_id) VALUES (?,?,?)";
            if ("0".equals(education_id)) {//批量添加部门
                String sql2 = "INSERT INTO department(NAME,school_id) VALUES (?,?)";
                int[] ints = organizationalStructureTemplate.batchUpdateDepartMent(sql2, schoolId);
                logger.info("添加部门 ints={}", ints.length);
                a = ints.length;
            } else if ("1".equals(education_id)) {//批量创建小学学部/年级和班级
                List<Long> longs = new ArrayList<>();
                List<String> strings = new ArrayList<String>();
                for (int i = 1; i < 7; i++) {
                    String grade = createGrade(i);
                    Long aLong = organizationalStructureTemplate.updateByParameterGetId(sql, grade, schoolId, integer, education_id);
                    longs.add(aLong);
                    strings.add(grade);
                }
                int[] ints = organizationalStructureTemplate.batchUpdate(sql1, longs, schoolId, strings);
                logger.info("添加小学部 ints={}", ints.length);
                a = ints.length;
            } else if ("2".equals(education_id)) {//批量创建初中学部/年级和班级
                List<Long> longs = new ArrayList<Long>();
                List<String> strings = new ArrayList<String>();
                for (int i = 1; i < 4; i++) {
                    String juniorHighSchool = createJuniorHighSchool(i);
                    Long aLong = organizationalStructureTemplate.updateByParameterGetId(sql, juniorHighSchool, schoolId, integer, education_id);
                    longs.add(aLong);
                    strings.add(juniorHighSchool);
                }
                int[] ints = organizationalStructureTemplate.batchUpdate(sql1, longs, schoolId, strings);
                logger.info("添加初中部 ints={}", ints.length);
                a = ints.length;
            } else if ("3".equals(education_id)) {//批量创建高中学部//年级和班级
                List<Long> longs = new ArrayList<>();
                List<String> strings = new ArrayList<String>();
                for (int i = 1; i < 4; i++) {
                    String s = buildingHighSchool(i);
                    Long aLong = organizationalStructureTemplate.updateByParameterGetId(sql, s, schoolId, integer, education_id);
                    longs.add(aLong);
                    strings.add(s);
                }
                int[] ints = organizationalStructureTemplate.batchUpdate(sql1, longs, schoolId, strings);
                logger.info("添加高中部 ints={}", ints.length);
                a = ints.length;
            }
        } catch (Exception e) {
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return a;
    }

    /**
     * @描述 添加部门
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int addDepartment(String schoolId, String departmentname) {
        String sql = "INSERT INTO department(name,school_id) VALUES (?,?)";
        return organizationalStructureTemplate.updateByParameter(sql, departmentname, schoolId);
    }

    /**
     * @描述 删除部门
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int delDepartment(String id) {
        String sql = "DELETE FROM department WHERE id=?";
        return organizationalStructureTemplate.updateByParameter(sql, id);
    }

    /**
     * @描述 修改部门
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int updateDepartment(String departmentname, String id) {
        String sql = "UPDATE department  SET NAME=? WHERE id=?";
        return organizationalStructureTemplate.updateByParameter(sql, departmentname, id);
    }

    /**
     * @描述 添加年级
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int addGrade(String schoolId, String education_id) {
        String sql1 = "SELECT name string FROM grade  WHERE school_id=? AND other=0 AND education_id=? ORDER BY id DESC LIMIT 1";
        String s = organizationalStructureTemplate.queryString(sql1, schoolId, education_id);
        String s1 = "";
        if ("1".equals(education_id)) {//小学部
            if ("六年级".equals(s)) {
                return 0;
            } else {
                s1 = createGrade(s);
            }
        } else if ("2".equals(education_id)) {//初中部
            if ("初三".equals(s)) {
                return 0;
            } else {
                s1 = createJuniorHighSchool(s);
            }
        } else if ("3".equals(education_id)) {//高中部
            if ("高三".equals(s)) {
                return 0;
            } else {
                s1 = buildingHighSchool(s);
            }
        }
        String sql = "INSERT INTO grade(name,school_id,department_id,other,education_id) VALUES (?,?,1,0,?)";
        return organizationalStructureTemplate.updateByParameter(sql, s1, schoolId, education_id);
    }

    /**
     * @描述 删除年级
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int delGrade(String id) {
        String sql = "DELETE FROM grade WHERE id=?";
        return organizationalStructureTemplate.updateByParameter(sql, id);
    }

    /**
     * @描述 修改其他 的名称
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int updateGrade(String name, String id) {
        String sql = "UPDATE grade  SET name=? WHERE id=? and other=1"; //支持其它 名称的修改
        return organizationalStructureTemplate.updateByParameter(sql, name, id);
    }

    /**
     * @描述 修改班级名称
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int updateClass(String name, String id) {
        String sql = "UPDATE classes  SET name=? WHERE id=? "; //支持其它 名称的修改
        int i = organizationalStructureTemplate.updateByParameter(sql, name, id);
        if (i > 0) {
            service.classesAndCards(id, "classflag", "1");
        }
        return i;
    }


    /**
     * @描述 删除班级
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int delClass(String id) {
        String sql = "DELETE FROM classes WHERE id=?";
        return organizationalStructureTemplate.updateByParameter(sql, id);
    }

    /**
     * @描述 添加班级
     * @创建人 zm
     * @创建时间 2019/12/8
     */
    @Override
    public int addClass(String schoolId, String name, String grade_id) {
        String sql = "INSERT INTO classes(name,school_id,grade_id) VALUES (?,?,?)";
        Integer  result = organizationalStructureTemplate.updateByParameter(sql, name, schoolId, grade_id);

        //创建线程，让线程去同步海威达部门
        HaiweidaDepartment h = new HaiweidaDepartment();
        h.setSchoolId(schoolId);
        Thread thread = new Thread(h);
        //开启线程
        thread.start();

        return result;
    }

    /**
     * @描述 根据年级查询班级数量
     * @创建人 zm
     * @创建时间 2019/12/11
     */
    @Override
    public int queryClass(String grade_id) {
        String sql = "SELECT  COUNT(1) count FROM  classes WHERE grade_id=?";
        return organizationalStructureTemplate.queryCount(sql, grade_id);
    }

    @Override
    public int queryClassCount(String classid) {
        String sql = "SELECT COUNT(1) count FROM  student WHERE class_id=?";
        return organizationalStructureTemplate.queryCount(sql, classid);
    }

    @Override
    public int queryGradeorClassCount(String schoolId) {
        String sql = "SELECT  COUNT(1) count FROM  classes WHERE school_id=?";
        String sql1 = "SELECT  COUNT(1) count FROM  grade WHERE school_id=?";
        Integer integer = organizationalStructureTemplate.queryCount(sql, schoolId);
        Integer integer1 = organizationalStructureTemplate.queryCount(sql1, schoolId);
        return integer + integer1;
    }

    @Override
    public int batchUpDateClass(ClassesList classesList) {
        String sql = "UPDATE classes SET second_name =?  WHERE id=?";
        return organizationalStructureTemplate.batchUpDateClass(sql, classesList);
    }

    public String createGrade(String i) {
        String name = "";
        if (i == null) {
            name = "一年级";
        }
        if ("一年级".equals(i)) {
            name = "二年级";
        }
        if ("二年级".equals(i)) {
            name = "三年级";
        }
        if ("三年级".equals(i)) {
            name = "四年级";
        }
        if ("四年级".equals(i)) {
            name = "五年级";
        }
        if ("五年级".equals(i)) {
            name = "六年级";
        }
        return name;
    }

    public String createGrade(int i) {
        String name = "";
        if (i == 1) {
            name = "一年级";
        }
        if (i == 2) {
            name = "二年级";
        }
        if (i == 3) {
            name = "三年级";
        }
        if (i == 4) {
            name = "四年级";
        }
        if (i == 5) {
            name = "五年级";
        }
        if (i == 6) {
            name = "六年级";
        }
        return name;
    }

    public String createJuniorHighSchool(int i) {
        String name = "";
        if (i == 1) {
            name = "初一";
        }
        if (i == 2) {
            name = "初二";
        }
        if (i == 3) {
            name = "初三";
        }
        return name;
    }

    public String createJuniorHighSchool(String i) {
        String name = "";
        if (i == null) {
            name = "初一";
        }
        if ("初一".equals(i)) {
            name = "初二";
        }
        if ("初二".equals(i)) {
            name = "初三";
        }
        return name;
    }

    public String buildingHighSchool(int i) {
        String name = "";
        if (i == 1) {
            name = "高一";
        }
        if (i == 2) {
            name = "高二";
        }
        if (i == 3) {
            name = "高三";
        }
        return name;
    }

    public String buildingHighSchool(String i) {
        String name = "";
        if (i == null) {
            name = "高一";
        }
        if ("高一".equals(i)) {
            name = "高二";
        }
        if ("高二".equals(i)) {
            name = "高三";
        }
        return name;
    }



}
